import { Provide } from '@midwayjs/core'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { Between, Repository } from 'typeorm'

import { DeleteDTO } from '@/dto'
import { SysLoginInfoEntity } from '@/entity'

import { FindLoginLogPageDTO } from './login-log.dto'

@Provide()
export class LoginLogService {
  @InjectEntityModel(SysLoginInfoEntity)
  loginInfoModel: Repository<SysLoginInfoEntity>

  async handleFindPage(dto: FindLoginLogPageDTO) {
    const { pageNum, pageSize, beginDate, endDate, ...where } = dto

    const [list, total] = await this.loginInfoModel.findAndCount({
      where: {
        ...where,
        loginDate: beginDate ? Between(beginDate, endDate) : null
      },
      order: {
        loginDate: 'DESC'
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize
    })

    return {
      pageNum,
      pageSize,
      total,
      list
    }
  }

  async handleDelete(dto: DeleteDTO) {
    const { ids } = dto

    await this.loginInfoModel.delete(ids)
  }

  async handleClear() {
    await this.loginInfoModel.clear()
  }
}
